package apigateway.project.core.filter;

import apigateway.project.core.context.GlobalContext;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
@Slf4j
public class GatewayFilterChain {
    private List<Filter> filters = new ArrayList<Filter>();

    public GatewayFilterChain addFilter(Filter filter) {
        filters.add(filter);
        return this;
    }

    public GatewayFilterChain addList(List<Filter> filters) {
        this.filters.addAll(filters);
        return this;
    }

    /**
     * 过滤器链执行过程
     * @param ctx
     * @return
     */
    public GlobalContext execute(GlobalContext ctx) {
        if(filters.isEmpty()) {
            return ctx;
        }
        try {
            for (Filter filter : filters) {
                filter.doFilter(ctx);
                if(ctx.getStatus()==GlobalContext.status_type.COMPLETED){
                    break;
                }
            }
        } catch (Exception e) {
            log.error("过滤器链发生异常:{}",e.getMessage());
            throw new RuntimeException(e);
        }
        return ctx;
    }
}
